#pragma once
#include <iostream>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <cstdlib>
#include <arpa/inet.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include "log.hpp"
using namespace std;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
};

const int backlog = 10;

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            log(Fatal, "socker error, %s: %d", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, %s: %d", strerror(errno), errno);
            exit(BIND_ERROR);
        }
    }
    void Listen()
    {
        if (listen(_sockfd, backlog) < 0)
        {
            log(Fatal, "listen error, %s: %d", strerror(errno), errno);
            exit(LISTEN_ERROR);
        }
    }
    int Accept(uint16_t *clientport, string *clientip)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int communication_sockfd = accept(_sockfd, (struct sockaddr *)&peer, &len);
        if (communication_sockfd < 0)
        {
            log(Warning, "accept error, %s: %d", strerror(errno), errno);
            return -1;
        }
        char ipstr[64];
        *clientport = ntohs(peer.sin_port);
        inet_ntop(AF_INET, &(peer.sin_addr), ipstr, sizeof(ipstr));
        *clientip = ipstr;
        return communication_sockfd;
    }
    bool Connect(const string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));
        int res = connect(_sockfd, (struct sockaddr *)&peer, sizeof(peer));
        if (res < 0)
        {
            cerr << "connect to " << ip << ":" << port << " error" << endl;
            return false;
        }
        return true;
        ;
    }
    void Close()
    {
        close(_sockfd);
    }
    int get_fd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};
